package partner

import (
	"gitee.com/binny_w/go-util"
	"github.com/gin-gonic/gin"
	"gopkg.in/natefinch/lumberjack.v2"
	"strings"
)

type Engine struct {
	E *gin.Engine
}

func NewEngine(mode, logFile string, logFormatter gin.LogFormatter) *Engine {
	gin.SetMode(mode)
	lumberjackLogger := &lumberjack.Logger{
		Filename:   logFile,
		MaxSize:    2,
		MaxAge:     100,
		MaxBackups: 10,
		LocalTime:  true,
		Compress:   false,
	}
	e := gin.New()
	cfg := gin.LoggerConfig{Output: lumberjackLogger}
	if logFormatter != nil {
		cfg.Formatter = logFormatter
	}
	e.Use(
		gin.LoggerWithConfig(cfg),
		gin.RecoveryWithWriter(lumberjackLogger),
		Cors(),
	)
	return &Engine{E: e}
}

func (e *Engine) RouterGroup(path string, handlers ...gin.HandlerFunc) *gin.RouterGroup {
	return e.E.Group(path, handlers...)
}

func (e *Engine) RegisterRouter(group *gin.RouterGroup, method, path string, handlers ...gin.HandlerFunc) gin.IRoutes {
	path = "/" + strings.TrimLeft(path, "/")
	if group == nil {
		return e.E.Handle(method, path, handlers...)
	}
	return group.Handle(method, path, handlers...)
}

func (e *Engine) RouterWithModel(group *gin.RouterGroup, model Model) {
	for m, a := range model.GinHandlers() {
		if a != nil {
			for p, hs := range a {
				e.RegisterRouter(group, m, p, hs...)
			}
		}
	}
}

func (e *Engine) UseMiddlewares(middlewares ...gin.HandlerFunc) {
	e.E.Use(middlewares...)
}

func (e *Engine) Run(addr string, onClose func()) {
	util.HttpSrvRun(addr, e.E, onClose)
}
